/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.yunyichina.provider.framework.annotation.validate;

import java.lang.reflect.Field;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Validate the @ValidateDigit annotation
 *
 * @author jiangtch
 */
public class ValidateDigitHandler implements Handler {

    private static final Logger logger = LoggerFactory.getLogger(ValidateDigitHandler.class);

    public void validate(AnnotationValidable validatedObj, Field field) throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "validate()");
        }
        if (field.isAnnotationPresent(ValidateDigit.class)) {
            checkDigit(validatedObj, field);
        }
    }

    /**
     * validate the String is digit only
     *
     * @param filter interceptor validated object
     * @param field  validated field or property
     * @throws ValidateException
     */
    private void checkDigit(AnnotationValidable filter, Field field) throws ValidateException {
        if (logger.isTraceEnabled()) {
            logger.trace(this.getClass().getName(), "checkDigit()");
        }
        
        Object valueObject;
        try {
            valueObject = GetFiledValue.getField(filter, field.getName());
        } catch (Exception ex) {
            logger.error("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
            throw new ValidateException("字段：" + field.getName() + " 获取值发生异常->" + ex.getMessage(), ex);
        }
        
        if(valueObject==null){
            return;
        }
        
        String value=String.valueOf(valueObject);        
        String patternStr = "\\d*";
        Pattern pattern = Pattern.compile(patternStr);
        if (value != null && !"".equals(value)) {
            if (!pattern.matcher(value).matches()) {
                logger.warn("字段：" + field.getName() + " 不是数字格式,检查的值为:" + value + ",请确认!");
                throw new ValidateException("字段：" + field.getName() + " 不是数字格式,检查的值为:" + value + ",请确认!");
            }
        }
    }

}
